/*
 * @Author: your name
 * @Date: 2021-04-16 09:49:02
 * @LastEditTime: 2021-05-22 16:33:42
 * @LastEditors: your name
 * @Description: In User Settings Edit
 * @FilePath: \egg-demo\app\middleware\jwt.js
 */
/* 
  options: 中间件的配置项，框架会将 app.config[${middlewareName}] 传递进来。// 注意是框架的中间件
  app: 当前应用 Application 的实例。
 */

module.exports = (options, app) => {
  return async function jwt( ctx, next) {
    const token = ctx.request.header.authorization;
    console.log('jwt options', options)
    console.log('jwt token', token)
    let decode = '';
    if(token) {
      try {
        decode = ctx.app.jwt.verify(token, options.secret, { 
          expiresIn: '60m', // 自定义过期时间
        });
        // decode = ctx.app.jwt.verify(token.split(' ')[1], options.secret);
        console.log('state.user before', ctx.state);
        ctx.state.user = decode;  // 解析之后的数据挂载到state.user
        console.log('state.user before next', ctx.state);
        await next();
        console.log('state.user after', ctx.state);
      } catch( err ) {
        ctx.helper.renderFail( ctx, { data: err, message: err})
        return
      }
    } else {
      ctx.helper.renderFail( ctx, { message: 'token is not exit'})
      return
    }
  }
}